import {Component, Input, OnInit} from '@angular/core';
//报警级别、类别数据模型
import {ApplicationService} from '../../../../service/application.service';
//列表数据模型
import {DataSourceService} from '../../../../service/data-source/data-source.service';
import {AlarmService} from '../../../../service/alarm/alarm.service';
import {DeviceAlarm} from '../../../../entity/alarm/alarm.model';
import {TurbineStatus} from '../turbineStatus.model';

@Component({
  selector: 'app-alarm-list',
  templateUrl: './alarm-list.component.html',
  styleUrls: ['./alarm-list.component.css'],
  providers: [DataSourceService]
})
export class AlarmListDetailComponent implements OnInit {
  public aalarmList: DeviceAlarm[] = [];
  public alarmList: DeviceAlarm[] = [];
  public alarmListCache: DeviceAlarm[] = [];
  @Input() turbineStatuses: TurbineStatus[] = [];
  public active: number = 2;
  first = 0;
  rows = 20;

  constructor(
    private dataSource: DataSourceService,
    private application: ApplicationService,
    private alarmService: AlarmService,
  ) {
  }

  ngOnInit() {
  }

  ngOnDestroy(): void {
    if (this.dataSource != null)
      this.dataSource.dispose();
  }

  upData(turbineIds: number[], startTime: Date, endTime: Date) {
    const aalarmList = this.alarmService.getDeviceAAlarm(turbineIds, '', '', 0, startTime.getTime() / 1000, endTime.getTime() / 1000);
    Promise.all([aalarmList])
      .then(res => {
        if (res[0]) {
          this.aalarmList = [];
          this.aalarmList = [...res[0]];
          this.dataSource.alarmDevice(turbineIds).subscribe(next => {
            this.resolving(next);
          });
        } else {
          throw new Error('查询失败！');
        }
      }).catch(res => {
      console.log('获取报警历史错误:', res)
    });
  }

  resolving(data: DeviceAlarm[]): void {
    data.forEach(d => {
      let flag = true;
      for (let i = 0, l = this.alarmListCache.length; i < l; i++) {
        let dd = this.alarmListCache[i]
        if (d.GN == dd.GN) {
          dd.faultLevelName = d.faultLevelName;
          dd.multipleValue = d.multipleValue;
          dd.faultBeginTime = d.faultBeginTime;
          dd.faultEndTime = d.faultEndTime;
          flag = false;
          break;
        }
      }
      if (flag) {
        this.alarmListCache.unshift(d);
      }
    });
    this.alarmList = this.alarmListCache;
  }

  onClickHeader(n: number) {
    this.active = n;
  }
}
